﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using PhotoGalleryEnteties;
using photogalleryMVC.Controllers;

namespace photogalleryMVC
{
    public class AccessToResourceAttribute : ActionFilterAttribute
    {
        private string _idParameterName;
        private ResourceType  _resourceType;

        public AccessToResourceAttribute(string idParameterName,ResourceType type)
        {
            _idParameterName = idParameterName;
            _resourceType = type;
        }

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            IDictionary<string, object> parameters = filterContext.ActionParameters;
            if (!parameters.ContainsKey(_idParameterName))
            {
                throw new Exception(string.Format("parameter with name {0} doesn`t exist", _idParameterName));
            }
            int id =(int) parameters[_idParameterName];
            PhotoGalleryController  controller = (PhotoGalleryController)filterContext.Controller;
            string ownerName;
            switch(_resourceType )
            {
                case ResourceType.Album :
                    ownerName = controller.AlbumRepository.GetAlbumById(id).Owner.UserName ;
                    break;
                case ResourceType .Photo :
                    ownerName = controller.PhotoRepository.GetPhotoInfo(id).Album.Owner.UserName ;
                    break;
                case ResourceType.Comment :
                    ownerName = controller.CommentRepository.GetComment(id).Author.UserName;
                    break;
                default:
                    throw new Exception("Unknown resource type");


            }
            

            if (string.Compare(ownerName , controller.User.Identity.Name, true) != 0 && !controller.User.IsInRole("admin"))
            {
                ViewDataDictionary<string[]> viewData = new ViewDataDictionary<string[]>(new string[]
                                                                                                 { "You havent got enough privilegies to perform this operation",});
                filterContext.Result = new ViewResult() { ViewName = "Error", ViewData = viewData };

            }

        }
    }

    public enum ResourceType{ Album,Photo,Comment}
}